
use std::{thread, time::{Duration, self}, borrow::Borrow};

use clap::Parser;
mod args_parse;
use args_parse::Args;
use serialport::FlowControl;

fn main() -> Result<(), ()> {
    let port = Args::parse().port;
    println!("open port {}",&port);
    let mut port = serialport::new(port, 921600)
        .timeout(std::time::Duration::from_millis(100)).flow_control(FlowControl::None)
        .open().unwrap();
    //重启模块
    println!("控制RTS重启。。。");
    port.write_request_to_send(true).unwrap();
    thread::sleep(Duration::from_millis(500));
    port.write_request_to_send(false).unwrap();

    let mut last = time::SystemTime::now();
    loop {
        let mut buff : [u8;2048] = [0;2048];
        let len = match port.read(&mut buff) {
            Err(e) => {
                if e.kind() == std::io::ErrorKind::TimedOut {//接收超时不算错误
                    0
                } else {
                    break
                }
            },
            Ok(r) => r,
        };
        //检查一下时间是不是超了
        let time = time::SystemTime::now().duration_since(last).unwrap();
        if time.as_secs() > 60 {
            println!("timeout!!");
            return Err(())
        }
        //没数据，不往下跑
        if len == 0 {
            continue;
        }
        let s = String::from_utf8_lossy(&buff[0..len]).into_owned();
        println!("[debug]{}",s);
        if s.starts_with('[') {
            println!("【匹配】{}",s);
            if s.starts_with("[FAIL]") {//失败了
                return Err(())
            }
            else if s.starts_with("[DONE]") {
                println!("【测试流程通过】");
                return Ok(())//结束了
            }
            last = time::SystemTime::now();
        }
    }
    println!("串口好像断了？");
    Err(())
}
